<template>
<div>
  <el-container>
    <el-aside class="productImage">   
      <el-image :src="Path.imgPath + props.selectedImage.imgs" class="popover-image" />
    </el-aside>
    <el-container>
        <el-header height="400px">
        <div class="productName"><span class="PnText">{{ props.selectedImage.name }}</span></div>
        <div class="productText"><span class="PtText">{{ props.selectedImage.description}}</span></div>
        <div class="productPrice"><span style="font-size: 20px; color: #ff3e3e; margin-left: 5%;">￥ </span><span class="PpText">{{ props.selectedImage.price}}</span></div>
          <el-form :model="form">
          <el-form-item style="margin-top: 5%;">
            <div style="display: flex;">
                <el-text style="font-size: medium; font-weight: 500;">配送至：</el-text>
                <el-select
                    v-model="form.address"
                    placeholder="选择地址"
                    style="width: 250px"
                  >
                    <el-option
                      v-for="item in props.address"
                      :key="item.id"
                      :label="item.linkAddress"
                      :value="item"
                    />
                  </el-select>
                  <el-popover
                    v-model="formshow"
                    placement="top-start"
                    title="新增地址"
                    :width="370"
                    trigger="click"
                    content="this is content, this is content, this is content"
                  >
                    <template #reference>
                      <el-button type="primary" plain style="margin-left: 10px; width: 80px;" class="m-2">新增地址</el-button>
                    </template>
                    <template #default>
                      <AddressAdd
                      @getAddress="emits('getAddress')"
                      v-model:formshow="formshow"/>
                    </template>
                  </el-popover>
              </div>
          </el-form-item>
        </el-form>
        <div style="align-items: center; display: flex; margin-top: 5%;">
            <express style="width: 10%; height: 10%; margin-left: 2%;"></express><span style="color: #646fb0; font-size: medium; font-weight: 600;">未来蜂物流 同城当日达 全国隔日达 可预约送货 </span>
          </div>
        </el-header>
        <el-main class="productSum" >
          <span style="margin-right: 5%; font-size: 20px;font-style: italic;">购买数量</span>
          <el-input-number  
            v-model="form.number"  
            @change="handleNumberChange"  
            :min="0"  
            label="数量"  
            controls-position="right"  
            style="height: 50px; margin-top: 5%; width: 30%;"  
          ></el-input-number>  
          <span style="margin-left: 5%; font-size: large;">库存: {{props.selectedImage.store}}件</span>
          <div style="margin-left: 0px; width: 250px;height: 50px; margin-top: 5%;" class="TtText">  
            总价: ￥{{ totalPrice }}  
          </div>  
        </el-main>
        <el-footer class="productCart">     
          <div style="display: flex;">
            <el-button type="primary" size="large" @click="add_order" :disabled="form.number <= 0">  
              <el-text  
                size="large"  
                style="padding: 50px; color: aliceblue; font-family: Arial, Helvetica, sans-serif; font-size: 20px;">  
                购买
              </el-text>  
            </el-button>  
            <el-button type="danger" size="large" @click="add_cart" >  
              <el-text  
                size="large"  
                style="padding: 50px; color: aliceblue; font-family: Arial, Helvetica, sans-serif; font-size: 20px;">  
                加入购物车  
              </el-text>  
            </el-button>
          </div>  
        </el-footer>  
    </el-container>
  </el-container>
</div>
</template>
<script setup>
import { ref, computed,reactive, watch} from 'vue';
import { ElImage,ElContainer,ElMessage,ElMessageBox } from 'element-plus';
import express from '@/components/storeByGrc/express.vue'
import AddressAdd from "@/components/form-wjq/addAddress.vue"
import { Path } from "@/constant/index"
import { get,post } from "@/plugins/axios"
import { useCartItemStore } from "@/stores/pinia"
import VueCookie from 'vue-cookies';
import router from '@/router';
const CartItemsStore = useCartItemStore();
const props = defineProps(['selectedImage','address'])
const emits = defineEmits(['getAddress','update:dialogVisible','getGoods'])
const form = reactive({
    product_name:'',
    address: '',
    sum:'',
    number:''
  })
  //购物数量
form.number = ref(0); // 初始化数字为0
const totalPrice = computed(() => {    
  let price = 0;  
  if (props.selectedImage && !isNaN(parseFloat(props.selectedImage.price))) {    
    price = parseFloat(props.selectedImage.price) * form.number;   
    price = Number(price.toFixed(2));  
    form.sum = price
  }    
  return price;    
});

function handleNumberChange(value) {  
  if (props.selectedImage && props.selectedImage.store !== undefined) {  
    const maxQuantity = parseInt(props.selectedImage.store, 10); 
    if (value > maxQuantity) {   
      form.number = maxQuantity;   
      ElMessage({  
        type: 'warning',  
        message: '购买数量不能超过库存数量！'  
      });  
    } else {  
      form.number = value;  
    }    
    totalPrice.value = parseFloat(props.selectedImage.price) * form.number;   
    form.sum = totalPrice.value.toFixed(2);  
  }  
}  
function add_cart(){
  if(!VueCookie.get('token')){
      router.push('/login')
  }else{
  ElMessageBox.confirm(
    '是否确认添加到购物车？',
    '提示',
    {
      confirmButtonText:'确认',
      cancelButtonText:'取消',
      type:'info'
    }
  ).then(()=>{
    post(Path.cartAdd,{
      goodId: props.selectedImage.id,
      count: 1,
    },content => {
      if(content){
        emits('getGoods')
        form.number = 0
        //location.reload();
        CartItemsStore.setSelectedGoods()
        // emits("update:dialogVisible",false)
      }
    })
  }).catch(()=>{
    ElMessage({
      type:'info',
      message:'成功取消',
    })
  })}
}

function add_order(){
  if(!VueCookie.get('token')){
      router.push('/login')
  }else{
  ElMessageBox.confirm(
    '是否确认购买？',
    '提示',
    {
      confirmButtonText:'确认',
      cancelButtonText:'取消',
      type:'info'
    }
  ).then(()=>{
    console.log("1111")
    console.dir(form.address)
    console.log("2222")
    if(form.address !== ''){
      post(Path.orderCreate,{
      goodId: props.selectedImage.id,
      count: form.number,
      linkUser: form.address.linkUser,
      linkAddress: form.address.linkAddress,
      linkPhone: form.address.linkPhone,
      totalPrice: totalPrice.value
    },content => {
      if(content){
        form.number = 0
        emits("update:dialogVisible",false)
        router.push("/trolley")
      }
    })
    } else {
      ElMessage.warning("请选择您的地址")
    }
  }).catch(()=>{
    ElMessage({
      type:'info',
      message:'成功取消',
    })
  })}
}
    
const dialogVisible = ref(false);

watch(dialogVisible, (newValue) => {  
  if (!newValue) {  
    form.number = 0
    form.address ='' 
  }  
});
</script>
<style scoped lang='scss'>
.productImage{
  width: 600px;
  box-shadow: inset;
  border-radius: 4%;
  margin-left: 4%;
  margin-right: 5%;
}
.productName{
  height: auto;
}
.productText{
  margin-top: 2%;
  height: auto;
}
.productPrice{
  height: 80px;
  background-color:#fff5f5;
  display: flex;
  align-items: center;
  margin-top: 5%;
}
.productCart{
  height:"200px"; 
  overflow:"none";
}

.PnText{
  font-size: 20px;
  font-weight: 1000;
}
.PtText{
  font-size: 14px;
}
.PpText{
  
  font-size: 30px;
  color: #ff3e3e;
}
.TtText{
  font-size: 20px;
  color: #ff3e3e;
}


.popover-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1000px;
  height: 500px;
} 

.popover-image {
  width: 100%;
  height: 98%;
  align-items: center
}

.input {
    height: 36px;
    width: 75%;
    border-radius: 4px;
  }
  
::v-deep .el-popover{
  min-width:500px;
}

</style>